<template>
  <el-dialog
    title="编辑管理信息"
    :visible.sync="formVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="5vh"
    width="400px"
    @close="closeDialog()"
  >
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules" :label-width="labelWidth" size="small">
      <el-row>
        <el-col :span="24">
          <el-form-item label="名称" prop="cflastname">
            <el-input v-model.trim="form.cflastname" disabled auto-complete="off" placeholder="请输入名称" />
          </el-form-item>
        </el-col>
        <el-form-item label="项目总" prop="xmzName">
          <el-input readonly v-model="form.xmzName" auto-complete="off" placeholder="请选择项目总">
            <el-button slot="append" icon="el-icon-user-solid" @click="openSelectUser('xmzFids', 'xmzName', true)" />
          </el-input>
        </el-form-item>
        <el-form-item label="项目工程负责人" prop="principalNames">
          <el-input readonly v-model="form.principalNames" auto-complete="off" placeholder="请选择项目工程负责人">
            <el-button slot="append" icon="el-icon-user-solid" @click="openSelectUser('principalIds', 'principalNames', true)" />
          </el-input>
        </el-form-item>
        <el-form-item label="项目经理" prop="xmjlName">
          <el-input readonly v-model="form.xmjlName" auto-complete="off" placeholder="请选择项目经理">
            <el-button slot="append" icon="el-icon-user-solid" @click="openSelectUser('xmjlId', 'xmjlName', true)" />
          </el-input>
        </el-form-item>
        <el-form-item prop="recorderCodes">
          <span slot="label">
            记录仪编码
            <el-tooltip placement="top" effect="light" content="只允许数字、字母、下划线，多个用半角逗号 “,” 隔开">
              <i class="el-icon-question" />
            </el-tooltip>
          </span>
          <el-input v-model.trim="form.recorderCodes" :maxlength="255" placeholder="请输入记录仪编码" />
        </el-form-item>
        <el-col :span="24">
          <el-form-item label="是否停工" prop="isLockout">
            <el-switch
              v-model="form.isLockout"
              active-color="#ff4949"
              inactive-color="#13ce66"
              active-text="停工"
              inactive-text="正常"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.isLockout == 1">
          <el-form-item label="停工时间" prop="lockoutDate">
            <el-date-picker
              v-model="form.lockoutDate"
              align="right"
              type="date"
              placeholder="请选择日期"
              value-format="yyyy-MM-dd"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.isLockout == 1">
          <el-form-item label="停工原因" prop="lockoutReason">
            <el-input v-model="form.lockoutReason" :maxlength="255" auto-complete="off" placeholder="请输入停工原因" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </div>
    <!-- 选择人员 -->
    <select-user-dialog
      :show.sync="showSelectUserVisible"
      :selected="selectedUser"
      @select="selectUserCallback"
      :max-num="maxNum"
    />
  </el-dialog>
</template>

<script>
import { updateSetInfo } from '@/api/baseManage/project'
import SelectUserDialog from '../../../components/SelectUserDialog.vue'
export default {
  name: 'SetInfoWd',
  components: { SelectUserDialog },
  props: {
    visible: { type: Boolean, default: false },
    labelWidth: { type: String, default: '100px' },
    info: { type: Object, default: _ => {} }
  },
  data() {
    return {
      form: {
        fid: '',
        xmzFids: '',
        xmzName: '',
        principalIds: '',
        principalNames: '',
        xmjlId: '',
        xmjlName: '',
        recorderCodes: '',
        isLockout: '',
        lockoutDate: '',
        lockoutReason: ''
      },
      formVisible: false,
      dataSourceVisible: false,
      currentDataSource: {},
      loading: false,
      rules: {
        cflastname: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        fnumber: [
          { required: true, message: '请输入编码', trigger: 'blur' }
        ],
        recorderCodes: [
          {
            trigger: 'blur',
            validator: (rule, val, cb) => {
              if (!val) return cb()
              for (const str of val.split(',')) {
                if (!str) return cb('不能逗号开头或结尾，逗号间每项不为空')
                if (/\W/.test(str)) return cb('只允许数字、字母、下划线，及半角逗号 “,”')
              }
              cb()
            }
          }
        ]
      },
      // 选择用户窗口
      showSelectUserVisible: false,
      // xmz principal
      selectUserOption: { idField: '', nameField: '', multi: false },
      selectedUser: [],
      // 最多选择人员个数
      maxNum: 5
    }
  },
  computed: {
    addModel() {
      return !this.info.fid
    }
  },
  watch: {
    visible(val) {
      this.formVisible = val
      if (val) {
        const info = JSON.parse(JSON.stringify(this.info))
        this.form.fid = info.fid || ''
        this.form.cflastname = info.cflastname || ''
        this.form.xmzFids = info.xmzFids || ''
        this.form.xmzName = info.xmzName || ''
        this.form.principalIds = info.principalIds || ''
        this.form.principalNames = info.principalNames || ''
        this.form.xmjlId = info.xmjlId || ''
        this.form.xmjlName = info.xmjlName || ''
        this.form.recorderCodes = info.recorderCodes || ''
        this.form.isLockout = info.isLockout || 0
        this.form.lockoutDate = info.lockoutDate || ''
        this.form.lockoutReason = info.lockoutReason || ''
      }
    }
  },
  methods: {
    /**
     * 关闭窗口
     */
    closeDialog() {
      this.requirements = []
      this.form.fid = ''
      this.$refs.form.resetFields()
      this.$emit('update:visible', false)
    },
    /**
     * 取消操作
     */
    cancel() {
      this.closeDialog()
    },
    // 打开选择用户
    openSelectUser(idField, nameField, multi) {
      this.selectUserOption = { idField, nameField, multi: !!multi }
      let selectedUser = []
      const idValue = this.form[idField] || ''
      const nameValue = this.form[nameField] || ''
      const ids = idValue ? idValue.split(',') : []
      const names = nameValue ? nameValue.split(',') : []
      if (ids.length && names.length) {
        selectedUser = ids.map((id, index) => ({ value: id, label: names[index] }))
      }
      this.selectedUser = selectedUser
      this.showSelectUserVisible = true
    },
    // 选择用户回调
    selectUserCallback(selection) {
      const { idField, nameField } = this.selectUserOption
      this.form[idField] = selection.map(i => i.value).join(',')
      this.form[nameField] = selection.map(i => i.label).join(',')
    },
    /**
     * 确认
     */
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.loading) {
            return
          }
          if (this.form.isLockout === 1 && (!this.form.lockoutDate || !this.form.lockoutReason)) {
            this.$message({ type: 'error', message: '请完整填写停工信息!' })
            return
          }
          if (!this.form.isLockout) {
            this.form.lockoutDate = null
            this.form.lockoutReason = ''
          }
          this.loading = true
          updateSetInfo(this.form).then(response => {
            this.$message({ type: 'success', message: '保存成功!' })
            this.$emit('change')
            this.closeDialog()
          }).finally(_ => {
            setTimeout(_ => {
              this.loading = false
            }, 500)
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
